package com.yonyou.wdt.service;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.LongSerializationPolicy;
import com.google.gson.reflect.TypeToken;
import com.yonyou.wdt.utils.RedisUtils;
import com.yonyou.wdt.utils.RequestTool;
import com.yonyou.wdt.utils.ResultCode;
import com.yonyou.wdt.utils.SelfBuildToken;
import com.yonyou.wdt.entity.QueryDto;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @author nishch
 * @version 3.0
 * @date 2020/3/11
 * @des 自建应用token替换为ISV生态应用token
 */
public abstract class BaseApi {

    private static final Logger logger = LoggerFactory.getLogger(BaseApi.class);
    // 设置默认的查询页码
    public static final String pageIndex = "1";
    // 设置默认的每页显示数量
    public static final String pageSize = "100";

    private static ObjectMapper mapper = new ObjectMapper();

    private static Gson gson = new Gson();

    // 自建应用token
    @Autowired
    private SelfBuildToken selfBuildToken;
    // public final void setSelfBuildToken(SelfBuildToken selfBuildToken){
    //     this.selfBuildToken = selfBuildToken;
    // }


    public <T> T doGet(String requestUrl, Map<String, Object> paramMap, Class<T> type, QueryDto dto) throws Exception {
        requestUrl = getUrl(requestUrl, dto);
        // String data=getRequestData1(RequestTool.doGet(requestUrl, paramMap,false));
        return mapper.readValue(getRequestData1(RequestTool.doGet(requestUrl, paramMap, false)), type);
    }

    public String doGet(String requestUrl, Map<String, Object> paramMap, QueryDto dto) throws Exception {
        requestUrl = getUrl(requestUrl, dto);

        return getRequestData1(RequestTool.doGet(requestUrl, paramMap, false));
    }

    public <T> T doPost(String requestUrl, Object param, Class<T> type, QueryDto dto) throws Exception {
        requestUrl = getUrl(requestUrl, dto);
        return mapper.readValue(getRequestData(RequestTool.doPost(requestUrl, param)), type);
    }

    public String doPost(String requestUrl, Object param, QueryDto dto) throws Exception {
        requestUrl = getUrl(requestUrl, dto);
        return getRequestData(RequestTool.doPost(requestUrl, param));
    }

    /**
     * post分页获取数据信息pageIndex,pageSize
     *
     * @return
     */
    public <T> T requestPostPage2(String requestUri, Map<String, Object> params, Class<T> type, QueryDto dto) throws Exception {
        if (null == params) {
            params = new HashMap<String, Object>();
        }
        if (!params.containsKey("pageIndex")) params.put("pageIndex", pageIndex);
        if (!params.containsKey("pageSize")) params.put("pageSize", pageSize);
        return doPost(requestUri, params, type, dto);
    }

    public String requestPostPage2(String requestUri, Map<String, Object> params, QueryDto dto) throws Exception {
        if (null == params) {
            params = new HashMap<String, Object>();
        }
        if (!params.containsKey("pageIndex")) params.put("pageIndex", pageIndex);
        if (!params.containsKey("pageSize")) params.put("pageSize", pageSize);
        return doPost(requestUri, params, dto);
    }


    protected String getRequestData(String json) throws Exception {
        String data = null;
        JSONObject parse = JSONUtil.parseObj(json);
        Gson gsonBuilder = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
        json = gsonBuilder.toJson(parse);
        Map result = gson.fromJson(json, new TypeToken<Map<String, Object>>() {
        }.getType());
        if (ResultCode.SUCCESS.getIndex().equals(result.get(ResultCode.SUCCESS.getName()))
                || ResultCode.SUCCESS2.getIndex().equals(result.get(ResultCode.SUCCESS2.getName()))) {
            data = gson.toJson(result);
        } else {
            logger.error(result.get("message").toString());
            // throw  new Exception(result.get("message").toString());
            data = gson.toJson(result);
        }
        return data;
    }

    protected String getRequestData1(String json) throws Exception {
        String data = null;
//        Map result = gson.fromJson(json,Map.class);
        JSONObject parse = JSONUtil.parseObj(json);
        Gson gsonBuilder = new GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create();
        json = gsonBuilder.toJson(parse);
        Map result = gson.fromJson(json, new TypeToken<Map<String, Object>>() {
        }.getType());
        if (ResultCode.SUCCESS.getIndex().equals(result.get(ResultCode.SUCCESS.getName()))
                || ResultCode.SUCCESS2.getIndex().equals(result.get(ResultCode.SUCCESS2.getName()))) {
            data = gson.toJson(result.get("data"));
        } else {
            logger.error(result.get("message").toString());
            // throw  new Exception(result.get("message").toString());
            data = gson.toJson(result.get("data"));
        }
        return data;
    }

    /**
     * 自建应用拼装token
     *
     * @param requestUri
     * @return
     * @throws Exception
     */
    protected String getUrl(String requestUri, QueryDto dto) throws Exception {
        String access_token = "";
        if (null != RedisUtils.get("Token:" + dto.getTenantId())) {
            access_token = (String) RedisUtils.get("Token:" + dto.getTenantId());
        } else {
            access_token = selfBuildToken.createToken(dto);
        }
        while ("".equals(access_token)) {
            access_token = selfBuildToken.createToken(dto);
        }
        return requestUri + "?access_token=" + access_token;
    }

}
